package il.technion.cs236369.dal;

import il.technion.cs236369.interfaces.ICacheEntry;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ByteArrayEntity;

/**
 * A basic implementation of ICacheEntry
 * 
 * @author Gal Lalouche 036933489 sgallal@t2
 * 
 */
class CacheEntryImpl implements ICacheEntry {
	private final String				_url;
	private final Map<String, String>	_headers	= new HashMap<String, String>();
	private final byte[]				_body;

	public CacheEntryImpl(String URL, HttpResponse response) throws IOException {
		_url = URL;
		for (Header header : response.getAllHeaders()) {
			_headers.put(header.getName(), header.getValue());
		}

		_body = IOUtils.toByteArray(response.getEntity().getContent());
		
		// return the entity for reread
		response.setEntity(new ByteArrayEntity(_body));
	}

	public CacheEntryImpl(String url, Map<String, String> headers, byte[] body) {
		_url = url;
		_headers.putAll(headers);

		_body = body;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Arrays.hashCode(_body);
		result = prime * result + ((_headers == null) ? 0 : _headers.hashCode());
		result = prime * result + ((_url == null) ? 0 : _url.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		CacheEntryImpl other = (CacheEntryImpl)obj;
		if (!Arrays.equals(_body, other._body))
			return false;
		if (_headers == null) {
			if (other._headers != null)
				return false;
		} else if (!_headers.equals(other._headers))
			return false;
		if (_url == null) {
			if (other._url != null)
				return false;
		} else if (!_url.equals(other._url))
			return false;
		return true;
	}

	@Override
	public String getURL() {
		return _url;
	}

	@Override
	public Map<String, String> getHeaders() {
		return _headers;
	}

	@Override
	public byte[] getBody() {
		return _body;
	}
}